package com.photoeditor.demo.ui.widget.image;

import android.animation.ObjectAnimator;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.av.edit.VideoToGifDevice;
import com.common.base.log.DLog;
import com.common.base.utils.DeviceUtils;
import com.photoeditor.R;
import com.photoeditor.demo.imageloader.ImageLoader;
import com.photoeditor.demo.model.bean.BitmapBean;
import com.photoeditor.demo.model.image.MediaBroadcastHelper;
import com.photoeditor.demo.model.image.PhotoViewAttacher;
import com.photoeditor.demo.model.image.gl.IPosition;
import com.photoeditor.demo.model.image.gl.TileViewCache;
import com.photoeditor.demo.model.image.util.ImageHelper;
import com.photoeditor.demo.model.preference.SPDataManager;
import com.photoeditor.demo.model.share.ShareImageCacheData;
import com.photoeditor.demo.model.share.ShareImageTools;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.statistics.StatisticsUtils;
import com.photoeditor.demo.ui.activity.GalleryActivity;
import com.photoeditor.demo.ui.activity.HomeActivity;
import com.photoeditor.demo.ui.activity.edit.EditorImageActivity;
import com.photoeditor.demo.ui.activity.edit.EditorVideoActivity;
import com.photoeditor.demo.ui.activity.edit.ImagePreviewActivity;
import com.photoeditor.demo.ui.adapter.share.ShareImageListAdapter;
import com.photoeditor.demo.ui.widget.share.ShareImageItem;
import com.photoeditor.demo.util.AsyncTask;
import com.photoeditor.demo.util.DepthPageTransformer;
import com.photoeditor.demo.util.FontUtil;
import com.photoeditor.demo.util.ILoadDiskCache;
import com.photoeditor.demo.util.MediaTypeUtil;
import com.photoeditor.demo.util.folder.FolderHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.Currency;
import java.util.Locale;

import pl.droidsonroids.gif.GifDrawable;

//import com.photoeditor.demo.ui.main.MainActivity;


/**
 * 图片预览界面
 */
public class ImagePreviewView extends RelativeLayout implements View.OnClickListener {

    private TileViewCache mViewCache;

    private static final String TAG = "ImagePreviewView";

    private View mTopPanel;
    private View mBottomPanel;
    private ImageView mBackView;
    private TextView mTitle;
    private ImageView mMediaTypeIndicator;

    private ImageView mGalleryBt;
    private ImageView mPhotoBt;
    private ImageView mGifBt;

    private PreViewPager mViewPager;
    private ImagePagerAdapter mAdapter;
    private boolean mIsSlideRight = true;

    //横屏时没有
    private View mButtomPanel;

    private View mSharePanel;
    private GridView mShareImageView;
    private ShareImageListAdapter mShareImageAdapter;
    private boolean mIsImageFirst = false;
    /*
     * 用于存储图片的URL
     */
    private ArrayList<BitmapBean> mUris;

    private Object mLockUrisObject = new Object();

    private final int NOT_SHOW_PANEL = 0x123;
    private final int SHOW_NUM = 0x234;
    private final int SHOW_IMAGE_NAME = 0x345;

    private final int BUTTOM_PANEL = 1;
    private final int TOP_PANEL = 2;
    private final int MEDIA_TYPE_INDICATOR = 3;


    private Animation mButtomPanelIn;
    private Animation mTopPanelIn;
    private Animation mButtomPanelOut;
    private Animation mTopPanelOut;
    private ObjectAnimator mMediaTypeIndicatorIn;
    private ObjectAnimator mMediaTypeIndicatorOut;

    private AlertDialog mDeleteConfirmDialog;

    private ProgressDialog mGetDataTaskProgressDialog;

    private ShareImageCacheData mShareCacheData;

    private boolean mIsLandscape;

    private ImagePreviewActivity mActivity;

    public int mLastPosition;

    private boolean mIsOther;

    private ProgressDialog mProgressDialog;

    private View mEmptyGalleryView;

    private ProgressDialog mShareDialog;

    private Dialog mPostcardTipsDialog;
    private ProgressDialog mUploadProgressDialog;

    /**
     * 用于记录当前是不是Action View
     */
    private boolean mIsActionView = false;

//    private LocationHelper mLocationHelper;

    //底部的按钮
    private ImageView mShare;
    private ImageView mEdit;
    private ImageView mDelete;

    private String mOtherBucketId;

    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == NOT_SHOW_PANEL) {
                if (!mIsLandscape) {
                    if (mButtomPanel.getVisibility() == View.VISIBLE) {
                        initAnimation(BUTTOM_PANEL, false);
                        mButtomPanel.setVisibility(View.GONE);
                        mButtomPanel.startAnimation(mButtomPanelOut);

                        if (mMediaTypeIndicator.getVisibility() == View.VISIBLE) {
                            mMediaTypeIndicatorOut.start();
                        }
                    }
                }
                if (mTopPanel.getVisibility() == View.VISIBLE) {
                    initAnimation(TOP_PANEL, false);
                    mTopPanel.startAnimation(mTopPanelOut);
                    mTopPanel.setVisibility(View.GONE);

                    if (mMediaTypeIndicator.getVisibility() == View.VISIBLE) {
                        mMediaTypeIndicatorOut.start();
                    }
                }
            } else if (msg.what == SHOW_NUM) {
                synchronized (mLockUrisObject) {
                    if (mUris != null) {
                        int i = msg.arg1 > mUris.size() ? mUris.size() : msg.arg1;
                        mTitle.setText(i + "/" + mUris.size());
                    }
                }
            } else if (msg.what == SHOW_IMAGE_NAME) {
                mTitle.setText(msg.obj != null ? msg.obj.toString() : null);
            }
            super.handleMessage(msg);
        }
    };


    public ImagePreviewView(ImagePreviewActivity context, boolean isFirstCreate, boolean isLandscape, boolean isOther) {
        super(context);
        mActivity = context;
        mIsLandscape = isLandscape;
        mIsOther = isOther;
        initView(isFirstCreate, 0, mIsOther);
    }

    /**
     * @param context
     * @param isLandscape 横竖屏
     * @param position
     */
    public ImagePreviewView(ImagePreviewActivity context, boolean isLandscape, int position) {
        super(context);
        mActivity = context;
        mIsLandscape = isLandscape;
        mIsOther = false;
        initView(true, position, mIsOther);
    }

    /**
     * @param context
     * @param isLandscape 横竖屏
     * @param position
     * @param isOther     是其他相册
     */
    public ImagePreviewView(ImagePreviewActivity context, boolean isLandscape, int position, boolean isOther) {
        super(context);
        mActivity = context;
        mIsLandscape = isLandscape;
        mIsOther = isOther;
        initView(true, position, mIsOther);
    }

    @Override
    protected void onVisibilityChanged(View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);
    }


    /**
     * 初始化
     */
    private void initView(boolean isFirstCreate, int position, boolean isOther) {
//        mLocationHelper = new LocationHelper(mActivity);
//        mLocationHelper.setupLocationListener();
        mViewCache = new TileViewCache(mActivity);
        LayoutInflater.from(getContext()).inflate(R.layout.activity_image_preview, this, true);
        mBottomPanel = findViewById(R.id.buttom_panel);
        //top panel
        mTopPanel = findViewById(R.id.top_panel);
        mBackView = (ImageView) findViewById(R.id.back);
        mTitle = (TextView) findViewById(R.id.title);
        FontUtil.setCustomFont(mTitle);
        mGalleryBt = (ImageView) findViewById(R.id.gallery_bt);
        mPhotoBt = (ImageView) findViewById(R.id.photo_bt);
        mGifBt = (ImageView) findViewById(R.id.gif_bt);
        mMediaTypeIndicator = (ImageView) findViewById(R.id.media_type_indicator);
        initAnimation(MEDIA_TYPE_INDICATOR, true);
        initAnimation(MEDIA_TYPE_INDICATOR, false);

        //imageview
        mViewPager = (PreViewPager) findViewById(R.id.image_view);
        mViewPager.setPageTransformer(true, new DepthPageTransformer());

        mShare = (ImageView) findViewById(R.id.share);
        mEdit = (ImageView) findViewById(R.id.edit);
        mDelete = (ImageView) findViewById(R.id.delete);

        position = Math.max(position, 0);
        mAdapter = new ImagePagerAdapter(getContext());
        if (isFirstCreate) {
            if (isOther) {
                mOtherBucketId = mActivity.getIntent().getStringExtra(ImagePreviewActivity.BUCKET_ID);
                startGettingOtherDataTask(position, mOtherBucketId);
            } else {
                gettingData(position, true);
            }
        } else {
            mViewPager.setPagingEnabled(false);
        }
        if (!mIsLandscape) {
            mButtomPanel = findViewById(R.id.buttom_panel);
        }

        bindViewListener();

        initView();
    }

    /**
     * 显示等待的Dialog
     */
    private void showWaitingForGetDataDialog() {
        View v = mActivity.getLayoutInflater().inflate(R.layout.progress_bar, null, false);
        mGetDataTaskProgressDialog = new ProgressDialog(getContext(), ProgressDialog.THEME_TRADITIONAL);
        mGetDataTaskProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mGetDataTaskProgressDialog.setCancelable(true);
        mGetDataTaskProgressDialog.setCanceledOnTouchOutside(false);
        mGetDataTaskProgressDialog.show();
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.gravity = Gravity.CENTER;
        mGetDataTaskProgressDialog.setContentView(v, lp);
        mGetDataTaskProgressDialog.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                if (mActivity.getEntrance() == ImagePreviewActivity.FROM_GALLERY
                        || mActivity.getEntrance() == ImagePreviewActivity.FROM_OTHER_GALLERY) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        mActivity.finishAfterTransition();
                    } else {
                        mActivity.finish();
//						mActivity.overridePendingTransition(R.anim.activity_bottom_out, 0);
                    }
                } else {
                    mActivity.finish();
                    mActivity.overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
                }
            }
        });
    }

    /**
     * 获取数据的异步任务
     *
     * @return
     */
    public AsyncTask<String, Integer, ArrayList<BitmapBean>> getGettingDataTask(final int position, final boolean isNeedCountPosition) {
        AsyncTask<String, Integer, ArrayList<BitmapBean>> mGetDataTask = new AsyncTask<String, Integer, ArrayList<BitmapBean>>() {

            @Override
            protected ArrayList<BitmapBean> doInBackground(String... params) {
                ArrayList<BitmapBean> result = null;
                if (Build.VERSION.SDK_INT >= 16) {
                    result = ImageHelper.getImageURIFromPath_SDK16(getContext(), null);
                } else {
                    result = ImageHelper.getImageURIFromPath_SDK15(getContext(), null);
                }
                return result;
            }

            @Override
            protected void onPostExecute(ArrayList<BitmapBean> result) {
                synchronized (mLockUrisObject) {
                    if (mGetDataTaskProgressDialog != null && mGetDataTaskProgressDialog.isShowing()) {
                        mGetDataTaskProgressDialog.dismiss();
                    }
                    mUris = result;
                    if (mUris == null || mUris.size() == 0) {//做一个保护
                        setEmptyGalleryViewVisibility(true);
                        return;
                    }
                    /**
                     * flag用于标识是否需要纠正position
                     */
                    boolean flag = false;
                    setEmptyGalleryViewVisibility(false);
                    int p;
                    if (flag) {//进行纠正
                        p = Math.min(mUris.size() - 1, position - 1);
                    } else {
                        p = Math.min(mUris.size() - 1, position);
                    }

                    if (mViewPager != null) {
                        mViewPager.setAdapter(mAdapter);
                        mViewPager.setCurrentItem(p);
                    }
                    refreshTopPanel(p);
                }
            }
        };
        return mGetDataTask;
    }

    /**
     * 获取数据的异步任务
     *
     * @return
     */
    public void startGettingOtherDataTask(final int position, final String bucket_id) {
        new AsyncTask<Void, Integer, ArrayList<BitmapBean>>() {

            @Override
            protected ArrayList<BitmapBean> doInBackground(Void... params) {
                ArrayList<BitmapBean> result = null;
                if (Build.VERSION.SDK_INT >= 16) {
                    result = ImageHelper.getImageURIFromBucketID_SDK16(getContext(), bucket_id);
                } else {
                    result = ImageHelper.getImageURIFromBucketID_SDK15(getContext(), bucket_id);
                }
                return result;
            }

            @Override
            protected void onPostExecute(ArrayList<BitmapBean> result) {
                synchronized (mLockUrisObject) {
                    mUris = result;
                    if (mUris == null || mUris.size() == 0) {//做一个保护
                        setEmptyGalleryViewVisibility(false);
                        return;
                    }
                    setEmptyGalleryViewVisibility(false);
                    int p = Math.min(mUris.size() - 1, position);
                    if (mViewPager != null) {
                        mViewPager.setAdapter(mAdapter);
                        mViewPager.setCurrentItem(p);
                    }
                    refreshTopPanel(p);
                }
            }
        }.executeOnExecutor(AsyncTask.DATABASE_THREAD_EXECUTOR);
    }

    /**
     * 分享界面初始化
     *
     * @param isFirst 用于表示是不是第一个界面（分享包含两个界面）
     */
    private void initShareImageView(boolean isFirst) {
        if (mSharePanel == null) {
            mShareCacheData = new ShareImageCacheData();
            ViewStub vs = (ViewStub) findViewById(R.id.share_iamge_viewstub_id);
            if (vs == null) {
                mSharePanel = findViewById(R.id.share_iamge_layout_id);
            } else {
                mSharePanel = vs.inflate();
            }
            mShareImageView = (GridView) mSharePanel.findViewById(R.id.share_gridview);
            mShareImageView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                                        int arg2, long arg3) {
                    if (arg1 instanceof ShareImageItem) {
                        ShareImageItem flag = (ShareImageItem) arg1;
                        if (flag.getItemData().getmPkgName() == null) {//Image 才有
                            synchronized (mLockUrisObject) {
                                int currentPosition = mViewPager.getCurrentItem();
                                BitmapBean bean = mUris.get(currentPosition);
                                initShareImageView(false);
                                initShareImageViewAdapter(false, MediaTypeUtil.isImage(bean.mType), MediaTypeUtil.isGif(bean.mType));
                                mShareImageAdapter.notifyDataSetChanged();
                            }
                        }
//						else if (flag.getItemData().getmPkgName().equals(ShareImageTools.PRINT_AS_PACKAGE_NAME)) {
//							BgDataPro.upLoadCustomStatisticsData(BgDataPro.CUSTOM_CLICK_SHARE_PRINT_AS);
//						}
                        else {
                            boolean isInstall = ShareImageTools.getAppIsInstalled(getContext(), flag.getItemData().getmPkgName());
                            boolean isImage = true;
                            boolean isGif = false;
                            synchronized (mLockUrisObject) {
                                int currentPosition = mViewPager.getCurrentItem();
                                BitmapBean bean = mUris.get(currentPosition);
                                isImage = MediaTypeUtil.isImage(bean.mType);
                                isGif = MediaTypeUtil.isGif(bean.mType);
                                if (isInstall) {
                                    final ShareImageItem.ShareImageItemData siid = flag.getItemData();
                                    mShareCacheData.setData(currentPosition, bean.mUri, siid.getmPkgName(), siid.getmActivityName());
                                    boolean result = true;
                                    if (ShareImageTools.INSTAGRAM_SEND_PIC_TO_SHARE_PACKAGE_NAME.equals(siid.getmPkgName())) {//Instagram不需要保存工具信息
                                        result = ShareImageTools.startInstagramShareActivity(getContext(), siid.getmPkgName(),
                                                siid.getmActivityName(), bean.mUri, MediaTypeUtil.isImage(bean.mType));
                                    } else {
                                        result = ShareImageTools.startShareActivity(getContext(), siid.getmPkgName(),
                                                siid.getmActivityName(), bean);
                                    }
                                    mSharePanel.setVisibility(View.GONE);
                                    if (result) {
                                        mSharePanel.setVisibility(View.GONE);
                                    } else {
                                        Toast.makeText(getContext(), R.string.not_install, Toast.LENGTH_SHORT).show();
                                    }
                                } else {
                                    Toast.makeText(getContext(), R.string.not_install, Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                    }
                }

            });
        }
        if (isFirst) {
            mIsImageFirst = true;
            mShareImageView.setPadding(mShareImageView.getPaddingLeft(),
                    mShareImageView.getPaddingTop(), mShareImageView.getPaddingRight(), DeviceUtils.dip2px(getContext(), 18));
        } else {
            mIsImageFirst = false;
            mShareImageView.setPadding(mShareImageView.getPaddingLeft(),
                    mShareImageView.getPaddingTop(), mShareImageView.getPaddingRight(), DeviceUtils.dip2px(getContext(), 10));
        }
    }

    /**
     * 初始化分享的Adapter
     *
     * @param isFirst 用于表示是不是第一个界面（分享包含两个界面）
     */
    private void initShareImageViewAdapter(boolean isFirst, boolean isImage, boolean isGif) {
        if (mShareImageAdapter == null) {
            if (isImage) {
                mShareImageAdapter = new ShareImageListAdapter(getContext(), ShareImageTools.getTop3ShareTools(getContext(), 1, true, !isGif));
            } else {
                mShareImageAdapter = new ShareImageListAdapter(getContext(), ShareImageTools.getTop3ShareTools(getContext(), 2, true, !isGif));
            }
        }
        if (mIsLandscape) {
            LayoutParams p = (LayoutParams) mSharePanel.getLayoutParams();
            int margin = getContext().getResources().getDimensionPixelSize(R.dimen.share_view_margin);
            p.leftMargin = margin;
            p.rightMargin = margin;
            mSharePanel.setLayoutParams(p);
        }
        if (isFirst) {
            LinearLayout.LayoutParams param = (LinearLayout.LayoutParams) mShareImageView.getLayoutParams();
            param.height = LinearLayout.LayoutParams.WRAP_CONTENT;
            mShareImageView.setLayoutParams(param);
            mShareImageAdapter.setData(ShareImageTools.getTop3ShareTools(getContext(), isImage ? 1 : 2, true, !isGif));
        } else {
            LinearLayout.LayoutParams param = (LinearLayout.LayoutParams) mShareImageView.getLayoutParams();
            param.height = ImagePreviewActivity.SCREEN_HEIGHT * 2 / 3 - getContext().getResources().getDimensionPixelSize(R.dimen.share_textview_height);
            mShareImageView.setLayoutParams(param);
            mShareImageAdapter.setData(ShareImageTools.getAllShareTools(getContext(), isImage));
        }
    }

    /**
     * 获取从其他相册进来时的 bucketId
     *
     * @return
     */
    public String getOtherBucketId() {
        return mOtherBucketId;
    }

    /**
     * 绑定监听
     */
    private void bindViewListener() {
        mShare.setOnClickListener(this);
        mEdit.setOnClickListener(this);
        mDelete.setOnClickListener(this);

        if (mActivity.getEntrance() == ImagePreviewActivity.FROM_BEAUTY || mActivity.getEntrance() == ImagePreviewActivity.FROM_OTHER) {
            mGalleryBt.setOnClickListener(this);
//            mGalleryBt.setVisibility(View.VISIBLE);
            mPhotoBt.setVisibility(View.GONE);
        } else {
//            mPhotoBt.setVisibility(View.VISIBLE);
            mPhotoBt.setOnClickListener(this);
            mGalleryBt.setVisibility(View.GONE);
        }


        if (mGifBt != null) {
            mGifBt.setOnClickListener(this);
        }

        if (mActivity.getIsViewAndShare()) {
            if (mIsLandscape) {
                mShare.setVisibility(View.GONE);
                mEdit.setVisibility(View.GONE);
                mDelete.setVisibility(View.GONE);
                mPhotoBt.setVisibility(View.GONE);
                mGalleryBt.setVisibility(View.GONE);
            } else {
                findViewById(R.id.share_layout).setVisibility(View.GONE);
                findViewById(R.id.edit_layout).setVisibility(View.GONE);
                findViewById(R.id.delete_layout).setVisibility(View.GONE);
                mPhotoBt.setVisibility(View.GONE);
                mGalleryBt.setVisibility(View.GONE);
            }
        }

        mBackView.setOnClickListener(this);
        mViewPager.addOnPageChangeListener(new OnPageChangeListener() {
            int lastValue = 0;
            boolean isScrolling = false;

            /**
             * arg0 就是当前的位置
             */
            @Override
            public void onPageSelected(int position) {
                refreshTopPanel(position);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                if (mSharePanel != null && mSharePanel.getVisibility() == View.VISIBLE) {
                    mSharePanel.setVisibility(View.GONE);
                }
                if (isScrolling) {
                    if (lastValue > arg2) {
                        mIsSlideRight = false;
                    } else if (lastValue < arg2) {
                        mIsSlideRight = true;
                    }
                }
                lastValue = arg2;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (state == 1) {
                    isScrolling = true;
                } else {
                    isScrolling = false;
                }
            }
        });
        mViewPager.setCurrentItem(0, false);
    }

    /**
     * 弹出分享界面时按下返回键会现退出分享界面
     */
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (mSharePanel != null && mSharePanel.getVisibility() == View.VISIBLE) {
            mSharePanel.setVisibility(View.GONE);
            return true;
        }
        return false;
    }

    public boolean onKeyBack() {
        return false;
    }

    /**
     * 处理点击事件
     * mShareView.performClick();只是为了显示改变
     */
    @Override
    public void onClick(View v) {
        int i1 = v.getId();
        if (i1 == R.id.share_layout || i1 == R.id.share) {
            synchronized (mLockUrisObject) {
                if (mUris == null || mUris.size() == 0) {
                    setEmptyGalleryViewVisibility(true);
                    return;
                }
                int p = mViewPager.getCurrentItem();
                BitmapBean bean = mUris.get(p);
                boolean isAble = bean.mIsAble;
                boolean isImage = MediaTypeUtil.isImage(bean.mType);
                if (isAble) {
                    // TODO: 17/4/20
                    mActivity.showShareDialog(null, bean);
                    StatisticsUtils.statisticsCustomPreviewClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_SHARE_CLICK);
                    StatisticsUtils.statisicsCustomFunction(StatisticsConstant.UMENG_CUSTOM_EVENT_EDITOR, StatisticsConstant.UMENG_CUSTOM_KEY_FUNCTION,
                            StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_SETTING_VALUE_SHARE_CLICK + StatisticsConstant.UMENG_CUSTOM_UNDER_LINE +
                                    SPDataManager.getFunctionEntrance() + StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_CLICK);
                } else {
                    Toast.makeText(getContext(), isImage ? R.string.image_broken : R.string.video_broken, Toast.LENGTH_SHORT).show();
                    StatisticsUtils.statisticsBrokenImg();
                }
            }

        } else if (i1 == R.id.edit_layout || i1 == R.id.edit) {
            synchronized (mLockUrisObject) {
                if (mUris == null || mUris.size() == 0) {
                    setEmptyGalleryViewVisibility(true);
                    return;
                }

                int position = mViewPager.getCurrentItem();
                final BitmapBean bean = mUris.get(position);
                boolean isAble = bean.mIsAble;
                boolean isImage = MediaTypeUtil.isImage(bean.mType);
                if (isAble) {
                    if (isImage) {//Image
                        if (!mIsActionView) {
                            EditorImageActivity.startImageEditActivity(mActivity, mUris.get(position).mUri, mUris.get(position).mDegree, ImagePreviewActivity.REFRESH_DATA);
                        } else {
                            EditorImageActivity.startImageEditActivity(mActivity, mUris.get(position).mUri, mUris.get(position).mDegree, ImagePreviewActivity.REFRESH_DATA_ACTION_VIEW);
                        }
                    } else if (MediaTypeUtil.isVideo(bean.mType)) {
//                        if (bean.mDuration > CollageActivity.MAX_DURATION_VIDEO
//                                && SPDataManager.needShowByond30sVideoTip()) {
//                             选中超过30s视频，第一次弹窗提示：超过30s视频会被裁剪成30s
//                            SPDataManager.setShowByond30sVideoTip(false);
//                            GalleryActivity.showSelBeyond30sVideoDialog(getContext(), new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//                                    VideoEditActivity.startVideoEditActivity(mActivity, bean.mPath, PicturePreviewActivity.REFRESH_DATA);
//                                }
//                            });
//                        } else {
                        EditorVideoActivity.startVideoEditActivity(mActivity, bean.mPath, ImagePreviewActivity.REFRESH_DATA);
//                        }
                    }
                    StatisticsUtils.statisticsCustomPreviewClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_EDITOR_CLICK);
                    mActivity.statisticsMainBtnPreviewEdit();
                } else {
                    Toast.makeText(getContext(), isImage ? R.string.image_broken : R.string.video_broken, Toast.LENGTH_SHORT).show();
                    StatisticsUtils.statisticsBrokenImg();
                }

            }
        } else if (i1 == R.id.delete_layout || i1 == R.id.delete) {
            synchronized (mLockUrisObject) {
                if (mUris == null || mUris.size() == 0) {
                    setEmptyGalleryViewVisibility(true);
                    return;
                }
                int currentPosition = mViewPager.getCurrentItem();
                boolean isimage = MediaTypeUtil.isImage(mUris.get(currentPosition).mType);
                mHandler.removeMessages(NOT_SHOW_PANEL);
                showDeleteConfirmDialog(isimage);
                StatisticsUtils.statisticsCustomPreviewClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_TRASH_CLICK);
                mActivity.statisticsMainBtnPreviewDelete();
            }

        } else if (i1 == R.id.back) {
            if (mActivity.getEntrance() == ImagePreviewActivity.FROM_GALLERY
                    || mActivity.getEntrance() == ImagePreviewActivity.FROM_OTHER_GALLERY) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    mActivity.finishAfterTransition();
                } else {
                    mActivity.finish();
                }
            } else if (mActivity.getEntrance() == ImagePreviewActivity.FROM_ADVANCE_FEATURE) {
                //goto home page
                HomeActivity.back2Home(mActivity);
            } else {
                mActivity.finish();
                mActivity.overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
            }
            StatisticsUtils.statisticsCustomPreviewClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_CANCEL_CLICK);
        } else if (i1 == R.id.gallery_bt) {
            if (mActivity.getEntrance() == ImagePreviewActivity.FROM_GALLERY ||
                    mActivity.getEntrance() == ImagePreviewActivity.FROM_OTHER_GALLERY) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    mActivity.finishAfterTransition();
                } else {
                    mActivity.finish();
//						mActivity.overridePendingTransition(R.anim.activity_bottom_out, 0);
                }
            } else {
                if (!mIsActionView) {
                    mLastPosition = getPosition();
                    clearMermory();
                    Intent i = new Intent(mActivity, GalleryActivity.class);
                    mActivity.startActivityForResult(i, ImagePreviewActivity.REQUEST_CODE_START_GALLERY);
                } else {//如果是从Action View进来的则返回时不用刷新
                    Intent i = new Intent(mActivity, GalleryActivity.class);
                    mActivity.startActivity(i);
                }
            }
            StatisticsUtils.statisticsCustomPreviewClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_ALBUM_CLICK);
        } else if (i1 == R.id.photo_bt) {
//            Intent intent = new Intent(mActivity, MainActivity.class);
//            intent.putExtra(ActionConstant.Extras.EXTRA_PAGE, MainActivity.PAGE_CAMERA);
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
//                    | Intent.FLAG_ACTIVITY_SINGLE_TOP
//                    | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//            mActivity.startActivity(intent);
//            mActivity.overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);

        } else if (i1 == R.id.gif_bt) {
            convertToGif();
            StatisticsUtils.statisticsCustomPreviewClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_GIF_CLICK);
        }
    }

    private void showDeleteConfirmDialog(boolean isImage) {
        if (mDeleteConfirmDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            builder.setTitle(R.string.image_preview_delete_dialog_tip);
            builder.setMessage(isImage ? R.string.image_preview_delete_dialog_message : R.string.image_preview_delete_dialog_message1);
            builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mDeleteConfirmDialog.dismiss();
                }
            });
            builder.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    synchronized (mLockUrisObject) {
                        int currentPosition = mViewPager.getCurrentItem();
                        boolean flag;
                        BitmapBean bean = mUris.get(currentPosition);
                        flag = ImageHelper.deleteMediaByUri(getContext(), bean.mUri, bean.mPath);
                        if (flag) {
                            if (mActivity.getEntrance() == ImagePreviewActivity.FROM_GALLERY) {
                                mActivity.setIsNeedRefresh(ImagePreviewActivity.REFRESH_CURRENT_AND_OTHER_GALLERY);
                            } else if (mActivity.getEntrance() == ImagePreviewActivity.FROM_OTHER_GALLERY) {
                                mActivity.setIsNeedRefresh(ImagePreviewActivity.REFRESH_CURRENT_AND_GALLERY);
                            }
                            mUris.remove(currentPosition);
                            mAdapter.notifyDataSetChanged();
                            if (mUris.size() == 0) {
                                mDeleteConfirmDialog.dismiss();
                                if (!mIsActionView) {
                                    setEmptyGalleryViewVisibility(true);
                                    return;
                                } else {
                                    mActivity.finish();
                                    return;
                                }
                            }
                            mViewPager.setAdapter(mAdapter);
                            currentPosition = currentPosition > mUris.size() - 1 ? mUris.size() - 1 : currentPosition;
                            mViewPager.setCurrentItem(currentPosition, true);
                            refreshTopPanel(currentPosition);
                            Toast.makeText(getContext(), R.string.delete_success, Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getContext(), R.string.delete_fail, Toast.LENGTH_SHORT).show();
                        }
                    }
                    mDeleteConfirmDialog.dismiss();
                }
            });
            mDeleteConfirmDialog = builder.create();
            mDeleteConfirmDialog.setCancelable(true);
            mDeleteConfirmDialog.setCanceledOnTouchOutside(false);
            mDeleteConfirmDialog.show();
            FontUtil.setAlertDialogCustomFont(mDeleteConfirmDialog);
        } else {
            mDeleteConfirmDialog.setMessage(getResources().getString(isImage ? R.string.image_preview_delete_dialog_message : R.string.image_preview_delete_dialog_message1));
            mDeleteConfirmDialog.show();
        }
    }

    /**
     * 处理Vip相关部分
     */
    public void onStart() {
        int count = mViewPager.getChildCount();
        for (int i = 0; i < count; i++) {
            View view = mViewPager.getChildAt(i);
            if (view instanceof PlayImageView) {
                PlayImageView playImageView = (PlayImageView) view;
                if (playImageView.getPosition() == mViewPager.getCurrentItem()) {
                    playImageView.start();
                }
            }
        }
    }

    public void onStop() {
        int count = mViewPager.getChildCount();
        for (int i = 0; i < count; i++) {
            View view = mViewPager.getChildAt(i);
            if (view instanceof PlayImageView) {
                PlayImageView playImageView = (PlayImageView) view;
                playImageView.stop();
            }
        }
    }

    /**
     * onDestroy
     */
    public void onDestroy() {
//        mLocationHelper.freeLocationListeners();
        MediaBroadcastHelper.getInstance().setScanCompletedListener(null);

        synchronized (mLockUrisObject) {
            if (mViewPager != null) {
                destoryTask();
                mViewPager.setAdapter(null);
            }
            if (mUris != null) {
                mUris.clear();
                mUris = null;
            }
        }
    }

    private void destoryTask() {
        int num = mViewPager.getChildCount();
        for (int i = 0; i < num; i++) {
            View v = mViewPager.getChildAt(i);
            if (v != null && v instanceof TiledBitmapView) {
//                TiledBitmapView view = (TiledBitmapView) v;
//                view.getImageView().recycle();
            }
        }
    }

    /**
     * 动画初始化
     *
     * @param key  用来代表是哪个空间
     * @param isIn 是否为进入动画
     */
    private void initAnimation(int key, boolean isIn) {
        if (key == BUTTOM_PANEL) {
            if (!mIsLandscape) {
                if (isIn) {
                    if (mButtomPanelIn == null) {
                        mButtomPanelIn = AnimationUtils.loadAnimation(mActivity, R.anim.bottom_in);
                        mButtomPanelIn.setDuration(200);
                    }
                } else {
                    if (mButtomPanelOut == null) {
                        mButtomPanelOut = AnimationUtils.loadAnimation(mActivity, R.anim.bottom_out);
                        mButtomPanelOut.setDuration(200);
                    }
                }
            }
        } else if (key == TOP_PANEL) {
            if (isIn) {
//				if(mTopPanelIn == null){
                mTopPanelIn = AnimationUtils.loadAnimation(mActivity, R.anim.top_in);
                mTopPanelIn.setDuration(200);
//				}
            } else {
//				if(mTopPanelOut == null){
                mTopPanelOut = AnimationUtils.loadAnimation(mActivity, R.anim.top_out);
                mTopPanelOut.setDuration(200);
//				}
            }
        } else if (key == MEDIA_TYPE_INDICATOR) {
            if (isIn) {
                mMediaTypeIndicatorIn = ObjectAnimator.ofFloat(mMediaTypeIndicator, "alpha", 0f, 1f);
            } else {
                mMediaTypeIndicatorOut = ObjectAnimator.ofFloat(mMediaTypeIndicator, "alpha", 1f, 0f);
            }
        }
    }

    /**
     * panel切换
     */
    private void switchPanel() {
        if (mIsLandscape) {
            if (mTopPanel.getVisibility() == View.GONE) {
                initAnimation(TOP_PANEL, true);
                mTopPanel.setVisibility(View.VISIBLE);
                mTopPanel.startAnimation(mTopPanelIn);

                if (mMediaTypeIndicator.getVisibility() == View.VISIBLE) {
                    mMediaTypeIndicatorIn.start();
                }
            } else {
                mHandler.removeMessages(NOT_SHOW_PANEL);
                mHandler.sendEmptyMessage(NOT_SHOW_PANEL);
            }
        } else {
            if (mButtomPanel.getVisibility() == View.GONE && mTopPanel.getVisibility() == View.GONE) {
                initAnimation(BUTTOM_PANEL, true);
                mButtomPanel.setVisibility(View.VISIBLE);
                mButtomPanel.startAnimation(mButtomPanelIn);

                initAnimation(TOP_PANEL, true);
                mTopPanel.setVisibility(View.VISIBLE);
                mTopPanel.startAnimation(mTopPanelIn);

                if (mMediaTypeIndicator.getVisibility() == View.VISIBLE) {
                    mMediaTypeIndicatorIn.start();
                }
            } else {
                mHandler.removeMessages(NOT_SHOW_PANEL);
                mHandler.sendEmptyMessage(NOT_SHOW_PANEL);
            }
        }
    }

    public void clickMenu() {
        if (mSharePanel != null && mSharePanel.getVisibility() == View.VISIBLE) {
            mSharePanel.setVisibility(View.GONE);
        } else {
            switchPanel();
        }
    }

    /**
     * 顶部栏内容刷新
     *
     * @param position
     */
    private void refreshTopPanel(int position) {
        Message msg = Message.obtain(mHandler, SHOW_NUM);
        msg.arg1 = position + 1;
        mHandler.sendMessage(msg);
        setOprationVisible(position);
        PlayImageView currentPlayImageView = null;
        int count = mViewPager.getChildCount();
        for (int i = 0; i < count; i++) {
            View view = mViewPager.getChildAt(i);
            if (view instanceof PlayImageView) {
                PlayImageView playImageView = (PlayImageView) view;
                if (playImageView.getPosition() != position) {
                    playImageView.pause();
                } else {
                    currentPlayImageView = playImageView;
                }
            }
        }
        if (currentPlayImageView != null) {
            currentPlayImageView.start();
        }
    }

    private void setOprationVisible(int position) {
        synchronized (mLockUrisObject) {
            position = Math.min(mUris.size() - 1, Math.max(position, 0));//数据保护

            BitmapBean bean = mUris.get(position);
            mShare.setAlpha(1f);
            mShare.setEnabled(true);
//            if (MediaTypeUtil.isVideo(bean.mType) && !FolderHelper.isMotionFilePath(bean.mPath)) {
//                mEdit.setAlpha(0.6f);
//                mEdit.setEnabled(false);
//            } else {
            mEdit.setAlpha(1f);
            mEdit.setEnabled(true);
//            }
            /*mEdit.setAlpha(1f);
            mEdit.setEnabled(true);*/
            mDelete.setAlpha(1f);
            mDelete.setEnabled(true);
            if (MediaTypeUtil.isGif(bean.mType)) {
                mMediaTypeIndicator.setImageResource(R.drawable.ic_preview_iocn_gif);
                mMediaTypeIndicator.setVisibility(View.VISIBLE);
                mGifBt.setVisibility(INVISIBLE);
            } else if (MediaTypeUtil.isVideo(bean.mType) && FolderHelper.isMotionFilePath(bean.mPath)) {
                mMediaTypeIndicator.setImageResource(R.drawable.ic_preview_iocn_play);
                mMediaTypeIndicator.setVisibility(View.VISIBLE);
                if (mTopPanel.getVisibility() == View.GONE) {
                    mMediaTypeIndicator.setAlpha(0f);
                } else {
                    mMediaTypeIndicator.setAlpha(1f);
                }
                if (SPDataManager.getShowImgPreviewDynamicTip()) {
                    SPDataManager.setShowImgPreviewDynamicTip(false);
                }
                mGifBt.setVisibility(View.VISIBLE);
            } else {
                mGifBt.setVisibility(INVISIBLE);
                mMediaTypeIndicator.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 编辑完后调用这个方法  添加到预览界面，需要注意的是广告
     *
     * @param uri
     */
    public void addUri(Uri uri) {
        synchronized (mLockUrisObject) {
            if (mUris == null) {
                mActivity.finish();
                return;
            }
            BitmapBean bean = ImageHelper.getInterBitmapBeanFormUri(getContext(), uri);
            if (bean != null) {
                mUris.add(0, bean);
                mAdapter.notifyDataSetChanged();
                mViewPager.setAdapter(mAdapter);
                mViewPager.setCurrentItem(0, true);
                refreshTopPanel(0);
            }
        }
    }

    /**
     * 这里需要深度复制
     *
     * @return
     */
    public ArrayList<BitmapBean> getData() {
        synchronized (mLockUrisObject) {
            if (mUris != null) {
                int l = mUris.size();
                ArrayList<BitmapBean> newList = new ArrayList<BitmapBean>(l);
                for (int i = 0; i < l; i++) {
                    newList.add(mUris.get(i));
                }
                return newList;
            } else {
                return null;
            }
        }
    }

    public int getPosition() {
        if (mViewPager != null) {
            return mViewPager.getCurrentItem();
        }
        return 0;
    }

    /**
     * 用于横屏时的处理
     *
     * @param uris
     * @param position
     * @param hasAd
     * @param adPosition
     */
    public void setData(ArrayList<BitmapBean> uris, int position, int hasAd, int adPosition) {
        synchronized (mLockUrisObject) {
            mUris = uris;
            if (mUris == null || mUris.size() == 0) {//做一个保护
                setEmptyGalleryViewVisibility(true);
                return;
            }
            setEmptyGalleryViewVisibility(false);
            position = Math.min(mUris.size() - 1, position);

            mViewPager.setPagingEnabled(true);
            mViewPager.setAdapter(mAdapter);
            mViewPager.setCurrentItem(position);
            refreshTopPanel(position);
        }
    }

    /**
     * 用于处理系统的android.intent.action.VIEW Intent
     *
     * @param uris
     */
    public void setData(ArrayList<BitmapBean> uris) {
        synchronized (mLockUrisObject) {
            mIsActionView = true;
            mUris = uris;
            if (mUris == null || mUris.size() == 0) {//做一个保护
                mActivity.finish();
                return;
            }
            setEmptyGalleryViewVisibility(false);
            mViewPager.setPagingEnabled(true);
            mViewPager.setAdapter(mAdapter);
            mViewPager.setCurrentItem(0);
            BitmapBean bean = mUris.get(0);
            if (bean == null || bean.mPath == null) {//做空指针保护
                mActivity.finish();
                return;
            }
            int index = bean.mPath.lastIndexOf(File.separator);
            String name = null;
            if (index == -1) {
                name = bean.mPath;
            } else {
                name = bean.mPath.substring(index + 1, bean.mPath.length());
            }
            Message msg = Message.obtain(mHandler, SHOW_IMAGE_NAME, name);
            mHandler.sendMessage(msg);
        }
    }

    public void dealActionViewActivityResult() {

    }

    /**
     * 清掉缓存 防止内存溢出
     */
    private void clearMermory() {
        synchronized (mLockUrisObject) {
            if (mViewPager != null) {
                destoryTask();
                mViewPager.setAdapter(null);
            }
            if (mUris != null) {
                mUris.clear();
            }
        }
    }

    /**
     * 初始化数据
     *
     * @param position
     */
    public void gettingData(final int position, final boolean isNeedCountPosition) {
        synchronized (MediaBroadcastHelper.getInstance()) {
            if (!MediaBroadcastHelper.getInstance().isWaiting()) {
                getGettingDataTask(position, isNeedCountPosition).executeOnExecutor(AsyncTask.DATABASE_THREAD_EXECUTOR);
            } else {
                MediaBroadcastHelper.getInstance().setScanCompletedListener(
                        new MediaBroadcastHelper.ScanCompletedListener() {

                            @Override
                            public void onScanCompleted() {
                                if (!mActivity.isFinishing()) {
                                    mActivity.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            getGettingDataTask(position, isNeedCountPosition).executeOnExecutor(AsyncTask.DATABASE_THREAD_EXECUTOR);
                                        }
                                    });
                                }
                            }
                        });
                showWaitingForGetDataDialog();
            }
        }
    }

    /**
     * 空View
     *
     * @return
     */
    private View getEmptyGalleryView() {
        if (mEmptyGalleryView == null) {
            ViewStub vs = (ViewStub) findViewById(R.id.empty_gallery_viewstub_id);
            if (vs != null) {
                mEmptyGalleryView = vs.inflate();
            } else {
                mEmptyGalleryView = findViewById(R.id.empty_gallery_layout_id);
            }
            if (mEmptyGalleryView != null) {
                TextView title = (TextView) mEmptyGalleryView.findViewById(R.id.empty_title);
                FontUtil.setCustomFont(title);
                TextView content = (TextView) mEmptyGalleryView.findViewById(R.id.empty_content);
                FontUtil.setCustomFont(title);
                View bt = mEmptyGalleryView.findViewById(R.id.empty_bt);
                title.setText(R.string.gallery_empty_title);
                content.setText(R.string.gallery_empty_content);
                bt.setVisibility(View.VISIBLE);
                bt.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
//                        Intent intent = new Intent(mActivity, MainActivity.class);
//                        intent.putExtra(ActionConstant.Extras.EXTRA_PAGE, MainActivity.PAGE_CAMERA);
//                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
//                                | Intent.FLAG_ACTIVITY_SINGLE_TOP
//                                | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                        mActivity.startActivity(intent);
                    }
                });
            }
        }
        return mEmptyGalleryView;
    }

    /**
     * 设置空View见或不见
     */
    private void setEmptyGalleryViewVisibility(boolean visible) {
        if (visible) {
            if (mIsLandscape) {
                mShare.setAlpha(0.6f);
                mShare.setEnabled(false);
                mEdit.setAlpha(0.6f);
                mEdit.setEnabled(false);
                mDelete.setAlpha(0.6f);
                mDelete.setEnabled(false);
            } else {
                mShare.setAlpha(0.6f);
                mShare.setEnabled(false);
                mEdit.setAlpha(0.6f);
                mEdit.setEnabled(false);
                mDelete.setAlpha(0.6f);
                mDelete.setEnabled(false);
            }
            mTitle.setText(null);
            getEmptyGalleryView().setVisibility(View.VISIBLE);
        } else {
            if (mEmptyGalleryView != null) {
                if (mIsLandscape) {
                    mShare.setAlpha(1f);
                    mShare.setEnabled(true);
                    mEdit.setAlpha(1f);
                    mEdit.setEnabled(true);
                    mDelete.setAlpha(1f);
                    mDelete.setEnabled(true);
                } else {
                    mShare.setAlpha(1f);
                    mShare.setEnabled(true);
                    mEdit.setAlpha(1f);
                    mEdit.setEnabled(true);
                    mDelete.setAlpha(1f);
                    mDelete.setEnabled(true);
                }
                mEmptyGalleryView.setVisibility(View.GONE);
            }
        }
    }

    public void initView() {

        if (mPhotoBt.getVisibility() == VISIBLE) {
            mPhotoBt.setImageResource(R.drawable.ic_preview_iocn_cam);
        }

        mGifBt.setImageResource(R.drawable.ic_preview_iocn_changegif);
        mViewPager.setBackgroundResource(R.drawable.preview_main_bg);
    }

    /**
     * ViewPager的Adapter
     */
    public class ImagePagerAdapter extends PagerAdapter {

        private Context mContext;
        private int mRefreshPosition;

        public ImagePagerAdapter(Context context) {
            this.mContext = context;
            mRefreshPosition = -1;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        private void refresh(int position) {
            mRefreshPosition = position;
            super.notifyDataSetChanged();
        }

        @Override
        public void notifyDataSetChanged() {
            mRefreshPosition = -1;
            super.notifyDataSetChanged();
        }

        /**
         * getView中View的类型增加时必须修改这个方法  不然广告会不正确
         */
        @Override
        public int getItemPosition(Object object) {
            if (mRefreshPosition == -1) {
                return POSITION_NONE;
            } else {
                int position = -2;
                if (object instanceof IPosition) {
                    position = ((IPosition) object).getPosition();
                }
                if (position == mRefreshPosition) {
                    return POSITION_NONE;
                } else {
                    return POSITION_UNCHANGED;
                }
            }
        }

        @Override
        public void destroyItem(ViewGroup container, int position,
                                Object object) {
            View view = (View) object;
            if (view instanceof PlayImageView) {
                PlayImageView v = (PlayImageView) view;
                v.stop();
            }
            container.removeView(view);
            if (view instanceof TiledBitmapView) {
                TiledBitmapView v = (TiledBitmapView) view;
                v.recycle();
            }
            mViewCache.dealEPosition(container, mViewPager.getCurrentItem());
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {

            synchronized (mLockUrisObject) {
                BitmapBean bean = mUris.get(position);

                {
                    int type = bean.mType;

                    if (MediaTypeUtil.isImage(type)) {
                        if (MediaTypeUtil.isGif(type)) {
                            BitmapImageView view = new BitmapImageView(mContext);
                            boolean isGif;
                            isGif = view.getImageView().setImageFile(bean.mPath);
                            view.getImageView().setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() {

                                @Override
                                public void onViewTap(View view, float x, float y) {//点击显示图片的View
                                    if (mSharePanel != null && mSharePanel.getVisibility() == View.VISIBLE) {
                                        mSharePanel.setVisibility(View.GONE);
                                    } else {
                                        switchPanel();
                                    }
                                }
                            });
                            if (mViewPager.getCurrentItem() == position) {
                                container.addView(view);
                            } else {
                                container.addView(view, 0);
                            }
                            if (!isGif) {
                                bean.mType = MediaTypeUtil.TYPE_OTHER_IMAGE;
                                showDisplayView(view, bean);
                                loadBitmapFromUri(position, view, mIsSlideRight);
                            }
                            Drawable drawable = view.getImageView().getDrawable();
                            if (drawable instanceof GifDrawable) {
                                ((GifDrawable) drawable).setLoopCount(65535);
                            }
                            loadDecoderFromPath(position, mIsSlideRight);
                            view.setPosition(position);

                            mViewCache.dealEPosition(container, mViewPager.getCurrentItem());
                            return view;
                        } else if (MediaTypeUtil.isJPGOrPNG(type)) {
                            final TiledBitmapView view = mViewCache.getView(mActivity);
//                            showDisplayView(view, bean);
                            view.getImageView().setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() {

                                @Override
                                public void onViewTap(View view, float x, float y) {//点击显示图片的View
                                    if (mSharePanel != null && mSharePanel.getVisibility() == View.VISIBLE) {
                                        mSharePanel.setVisibility(View.GONE);
                                    } else {
                                        switchPanel();
                                    }
                                }
                            });
                            int degree = mActivity.getIntent().getIntExtra("degree", 0);
                            ImageLoader.loadImageWithThumbnail(mActivity, bean.mPath, degree, -1, view.getImageView(),
                                    new ImageLoader.OnLoadBitmapListener() {
                                        @Override
                                        public void onLoadBitmapFinish(Object bitmap) {
                                            if (bitmap != null) {
                                                view.setDisplayViewGone();
                                            } else {
                                                try {
//                                                    dealBrokenMedia(view);
                                                } catch (Exception e) {
                                                }
                                            }
                                        }
                                    });
                            if (mViewPager.getCurrentItem() == position) {
                                container.addView(view);
                            } else {
                                container.addView(view, 0);
                            }
                            loadDecoderFromPath(position, mIsSlideRight);
                            view.setPosition(position);

                            mViewCache.dealEPosition(container, mViewPager.getCurrentItem());
                            return view;
                        } else {
                            BitmapImageView view = new BitmapImageView(mContext);
                            showDisplayView(view, bean);
                            view.getImageView().setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() {

                                @Override
                                public void onViewTap(View view, float x, float y) {//点击显示图片的View
                                    if (mSharePanel != null && mSharePanel.getVisibility() == View.VISIBLE) {
                                        mSharePanel.setVisibility(View.GONE);
                                    } else {
                                        switchPanel();
                                    }
                                }
                            });
                            if (mViewPager.getCurrentItem() == position) {
                                container.addView(view);
                            } else {
                                container.addView(view, 0);
                            }
                            loadBitmapFromUri(position, view, mIsSlideRight);
                            loadDecoderFromPath(position, mIsSlideRight);
                            view.setPosition(position);

                            mViewCache.dealEPosition(container, mViewPager.getCurrentItem());
                            return view;
                        }
                    } else if (FolderHelper.isMotionFilePath(bean.mPath)) {
                        PlayImageView view = new PlayImageView(mContext);
                        showDisplayView(view, bean);
                        view.setVideoImageViewListener(new OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                if (mSharePanel != null && mSharePanel.getVisibility() == View.VISIBLE) {
                                    mSharePanel.setVisibility(View.GONE);
                                } else {
                                    switchPanel();
                                }
                            }
                        });
                        view.setup(container, bean, mViewPager.getCurrentItem() == position);
                        loadBitmapFromUri(position, view, mIsSlideRight);
                        loadDecoderFromPath(position, mIsSlideRight);
                        view.setPosition(position);
                        if (position == mViewPager.getCurrentItem()) {
                            view.start();
                        }
                        mViewCache.dealEPosition(container, mViewPager.getCurrentItem());
                        return view;
                    } else {//视频
                        VideoImageView view = new VideoImageView(mContext);
                        showDisplayView(view, bean);
                        view.setPlayVideoListener(new OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                ImageHelper.startVideoPlayer(mContext, mUris.get(position).mUri);
                            }
                        });
                        view.setVideoImageViewListener(new OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                if (mSharePanel != null && mSharePanel.getVisibility() == View.VISIBLE) {
                                    mSharePanel.setVisibility(View.GONE);
                                } else {
                                    switchPanel();
                                }
                            }
                        });
                        if (mViewPager.getCurrentItem() == position) {
                            container.addView(view);
                        } else {
                            container.addView(view, 0);
                        }
                        loadBitmapFromUri(position, view, mIsSlideRight);
                        loadDecoderFromPath(position, mIsSlideRight);
                        view.setPosition(position);

                        mViewCache.dealEPosition(container, mViewPager.getCurrentItem());
                        return view;
                    }
                }
            }
        }

        @Override
        public int getCount() {
            synchronized (mLockUrisObject) {
                if (mUris == null) {
                    return 0;
                } else {
                    return mUris.size();
                }
            }
        }

        private void loadBitmapInfo(final BitmapBean bean) {
            ImageLoader.loadImageOnlyStrongRef(mActivity, bean.mPath, new ImageLoader.OnLoadBitmapListener() {
                @Override
                public void onLoadBitmapFinish(Object bitmap) {
                    synchronized (mLockUrisObject) {
                        if (bitmap != null && bitmap instanceof Bitmap) {
                            bean.mWidth = ((Bitmap) bitmap).getWidth();
                            bean.mHeight = ((Bitmap) bitmap).getHeight();
                        } else {
                            bean.mIsAble = false;
                        }
                    }
                }
            });
        }

        /**
         * 解析视频并显示
         *
         * @param position
         * @param isSlideRight
         */
        private void loadBitmapFromUri(final int position, View v, boolean isSlideRight) {
            if (position == 0) {
                BitmapBean bean = mUris.get(position);
                if (!MediaTypeUtil.isJPGOrPNG(bean.mType) && !MediaTypeUtil.isGif(bean.mType)) {
                    if (bean.mIsAble) {
                        loadBitmapInfo(bean);
                    } else {
                        dealBrokenMedia(v);
                    }
                }
            } else {
                BitmapBean bean = mUris.get(position);
                if (!MediaTypeUtil.isJPGOrPNG(bean.mType) && !MediaTypeUtil.isGif(bean.mType)) {
                    if (bean.mIsAble) {
                        loadBitmapInfo(bean);
                    } else {
                        dealBrokenMedia(v);
                    }
                }
                if (isSlideRight) {//position 增加
                    if (position + 3 < mUris.size()) {
                        BitmapBean bean3 = mUris.get(position + 3);
                        if (!MediaTypeUtil.isJPGOrPNG(bean3.mType) && !MediaTypeUtil.isGif(bean3.mType)) {
                            if (bean3.mIsAble) {
                                loadBitmapInfo(bean3);
                            }
                        }
                    }
                    if (position + 2 < mUris.size()) {
                        BitmapBean bean2 = mUris.get(position + 2);
                        if (!MediaTypeUtil.isJPGOrPNG(bean2.mType) && !MediaTypeUtil.isGif(bean2.mType)) {
                            if (bean2.mIsAble) {
                                loadBitmapInfo(bean2);
                            }
                        }
                    }
                    if (position + 1 < mUris.size()) {
                        BitmapBean bean1 = mUris.get(position + 1);
                        if (!MediaTypeUtil.isJPGOrPNG(bean1.mType) && !MediaTypeUtil.isGif(bean1.mType)) {
                            if (bean1.mIsAble) {
                                loadBitmapInfo(bean1);
                            }
                        }
                    }
                } else {//position 减少
                    if (position - 3 > 0) {
                        BitmapBean bean3 = mUris.get(position - 3);
                        if (!MediaTypeUtil.isJPGOrPNG(bean3.mType) && !MediaTypeUtil.isGif(bean3.mType)) {
                            if (bean3.mIsAble) {
                                loadBitmapInfo(bean3);
                            }
                        }
                    }
                    if (position - 2 > 0) {
                        BitmapBean bean2 = mUris.get(position - 2);
                        if (!MediaTypeUtil.isJPGOrPNG(bean2.mType) && !MediaTypeUtil.isGif(bean2.mType)) {
                            if (bean2.mIsAble) {
                                loadBitmapInfo(bean2);
                            }
                        }
                    }
                    if (position - 1 > 0) {
                        BitmapBean bean1 = mUris.get(position - 1);
                        if (!MediaTypeUtil.isJPGOrPNG(bean1.mType) && !MediaTypeUtil.isGif(bean1.mType)) {
                            if (bean1.mIsAble) {
                                loadBitmapInfo(bean1);
                            }
                        }
                    }
                }
            }
        }

        private void loadDecoderFromPath(final int position, boolean isSlideRight) {
            if (isSlideRight) {//position 增加
                if (position + 3 < mUris.size()) {
                    BitmapBean bean3 = mUris.get(position + 3);
                    if (MediaTypeUtil.isJPGOrPNG(bean3.mType) && bean3.mIsAble) {
                        ImageLoader.loadImageOnly(mActivity, bean3.mPath, null);
                    }
                }
                if (position + 2 < mUris.size()) {
                    BitmapBean bean2 = mUris.get(position + 2);
                    if (MediaTypeUtil.isJPGOrPNG(bean2.mType) && bean2.mIsAble) {
                        ImageLoader.loadImageOnly(mActivity, bean2.mPath, null);
                    }
                }
            } else {//position 减少
                if (position - 3 > 0) {
                    BitmapBean bean3 = mUris.get(position - 3);
                    if (MediaTypeUtil.isJPGOrPNG(bean3.mType) && bean3.mIsAble) {
                        ImageLoader.loadImageOnly(mActivity, bean3.mPath, null);
                    }
                }
                if (position - 2 > 0) {
                    BitmapBean bean2 = mUris.get(position - 2);
                    if (MediaTypeUtil.isJPGOrPNG(bean2.mType) && bean2.mIsAble) {
                        ImageLoader.loadImageOnly(mActivity, bean2.mPath, null);
                    }
                }
            }
        }

        private void dealBrokenMedia(View v) {
            if (v instanceof BitmapImageView) {
                BitmapImageView view = ((BitmapImageView) v);
                TextView tv = new TextView(mContext);
                tv.setText(R.string.image_broken);
                tv.setTextColor(0x7fffffff);
                LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                lp.addRule(RelativeLayout.BELOW, R.id.display_view);
                lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
                lp.topMargin = getResources().getDimensionPixelSize(R.dimen.load_error_margin_top);
                view.getDisplayLayout().addView(tv, lp);

                ImageView dv = view.getDisplayView();
                LayoutParams dlp = (LayoutParams) dv.getLayoutParams();
                dlp.width = LayoutParams.WRAP_CONTENT;
                dlp.height = LayoutParams.WRAP_CONTENT;
                dv.setLayoutParams(dlp);
                dv.setBackgroundDrawable(null);
                dv.setImageResource(R.drawable.ic_load_image_broken);
                view.getImageView().setImageResource(R.color.transpant);

                view.setDisplayLayoutPaddingBottom(R.dimen.load_error_move);
            } else if (v instanceof VideoImageView) {
                VideoImageView view = ((VideoImageView) v);
                TextView tv = new TextView(mContext);
                tv.setText(R.string.video_broken);
                tv.setTextColor(0x7fffffff);
                LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                lp.addRule(RelativeLayout.BELOW, R.id.display_view);
                lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
                lp.topMargin = getResources().getDimensionPixelSize(R.dimen.load_error_margin_top);
                view.getDisplayLayout().addView(tv, lp);

                ImageView dv = view.getDisplayView();
                LayoutParams dlp = (LayoutParams) dv.getLayoutParams();
                dlp.width = LayoutParams.WRAP_CONTENT;
                dlp.height = LayoutParams.WRAP_CONTENT;
                dv.setLayoutParams(dlp);
                dv.setBackgroundDrawable(null);
                dv.setImageResource(R.drawable.ic_load_image_broken);
                view.getVideoImageView().setImageResource(R.color.transpant);

                view.setDisplayLayoutPaddingBottom(R.dimen.load_error_move);
                view.setPlayViewGone();
            } else if (v instanceof TiledBitmapView) {
                TiledBitmapView view = ((TiledBitmapView) v);
                TextView tv = new TextView(mContext);
                tv.setText(R.string.image_broken);
                tv.setTextColor(0x7fffffff);
                LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                lp.addRule(RelativeLayout.BELOW, R.id.display_view);
                lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
                lp.topMargin = getResources().getDimensionPixelSize(R.dimen.load_error_margin_top);
                view.getDisplayLayout().addView(tv, lp);

                ImageView dv = view.getDisplayView();
                LayoutParams dlp = (LayoutParams) dv.getLayoutParams();
                dlp.width = LayoutParams.WRAP_CONTENT;
                dlp.height = LayoutParams.WRAP_CONTENT;
                dv.setLayoutParams(dlp);
                dv.setBackgroundDrawable(null);
                dv.setImageResource(R.drawable.ic_load_image_broken);

                view.setDisplayLayoutPaddingBottom(R.dimen.load_error_move);
            }
        }

        /**
         * 显示默认的底图
         *
         * @param bview
         * @param bean
         */
        private void showDisplayView(ILoadDiskCache bview, final BitmapBean bean) {

            final ImageView v = bview.getDisplayView();
            ImageLoader.loadImage(mActivity, bean.mPath, -1, v,
                    new ImageLoader.OnLoadBitmapListener() {
                        @Override
                        public void onLoadBitmapFinish(Object bitmap) {
                            if (bitmap == null) {
                                if (v.getDrawable() == null) {
                                    int a[] = ImageHelper.getKnownBitmapSize(bean, ImagePreviewActivity.SCREEN_WIDTH, ImagePreviewActivity.SCREEN_HEIGHT);
                                    ViewGroup.LayoutParams rlp = v.getLayoutParams();
                                    v.setScaleType(ScaleType.CENTER);
                                    rlp.height = a[1];
                                    rlp.width = a[0];
                                    v.setLayoutParams(rlp);
                                    v.setBackgroundResource(R.color.image_background);
                                    v.setImageResource(R.drawable.ic_image_default);
                                }
                            }
                        }
                    });
        }
    }

    private void showProgressDialog(String title, int max, boolean cancelable, boolean showNumber) {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(mActivity, ProgressDialog.THEME_HOLO_LIGHT);
            mProgressDialog.setCanceledOnTouchOutside(false);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        }

        hideProgressDialog();
        mProgressDialog.setProgressNumberFormat(showNumber ? "%1d/%2d" : null);
        mProgressDialog.setCancelable(cancelable);
        mProgressDialog.setTitle(title);
        mProgressDialog.setMax(max);
        mProgressDialog.show();
        mProgressDialog.setProgress(0);
    }

    private void hideProgressDialog() {
        try {
            if (mProgressDialog != null && mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
            }
        } catch (Throwable tr) {
            DLog.e(TAG, "", tr);
        }
    }

    private void showUploadProgressDialog(String title, int max, boolean cancelable, boolean showNumber) {
        if (mUploadProgressDialog == null) {
            mUploadProgressDialog = new ProgressDialog(mActivity, ProgressDialog.THEME_HOLO_LIGHT);
            mUploadProgressDialog.setCanceledOnTouchOutside(false);
            mUploadProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        }

        hideUploadProgressDialog();
        mUploadProgressDialog.setProgressNumberFormat(showNumber ? "%1d/%2d" : null);
        mUploadProgressDialog.setCancelable(cancelable);
        mUploadProgressDialog.setTitle(title);
        mUploadProgressDialog.setMax(max);
        mUploadProgressDialog.show();
        mUploadProgressDialog.setProgress(0);
    }

    private void hideUploadProgressDialog() {
        try {
            if (mUploadProgressDialog != null && mUploadProgressDialog.isShowing()
                    && !mActivity.isFinishing()) {
                mUploadProgressDialog.dismiss();
            }
        } catch (Throwable tr) {
            Log.e(TAG, "", tr);
        }
    }

    private String getCurrency(Locale locale) {
        if (Currency.getInstance(locale).getCurrencyCode().equals("GBP"))
            return "GBP";
        if (Currency.getInstance(locale).getCurrencyCode().equals("EUR"))
            return "EUR";
        return "USD";
    }

    private void convertToGif() {
        synchronized (mLockUrisObject) {
            if (mUris == null || mUris.size() == 0) {
                setEmptyGalleryViewVisibility(true);
                return;
            }

            int position = mViewPager.getCurrentItem();
            BitmapBean bean = mUris.get(position);
            if (MediaTypeUtil.isVideo(bean.mType) && FolderHelper.isMotionFilePath(bean.mPath) && bean.mIsAble) {
                try {
                    VideoToGifDevice device = new VideoToGifDevice(new File(bean.mPath),
                            FolderHelper.getOutputMediaFile(mActivity, FolderHelper.MEDIA_TYPE_GIF, false),
                            new VideoToGifDevice.ResultCallback() {
                                @Override
                                public void onError(final File outputFile) {
                                    outputFile.delete();
                                    mActivity.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (outputFile != null) {
                                                outputFile.delete();
                                            }
                                            hideUploadProgressDialog();
                                            Toast.makeText(mActivity, R.string.video_edit_save_failed,
                                                    Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }

                                @Override
                                public void onProgressUpdate(final float progress) {
                                    mActivity.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (mUploadProgressDialog != null) {
                                                mUploadProgressDialog.setProgress((int) (progress * 100 + 0.5f));
                                            }
                                        }
                                    });
                                }

                                @Override
                                public void onSuccess(final File outputFile) {
                                    final BitmapFactory.Options options = new BitmapFactory.Options();
                                    options.inSampleSize = 1;
                                    options.inJustDecodeBounds = true;
                                    BitmapFactory.decodeFile(outputFile.getAbsolutePath(), options);
                                    new Thread() {
                                        @Override
                                        public void run() {
                                            super.run();
                                            File checkedFile = FolderHelper.checkMoveToExtSdcard(mActivity, outputFile, options.outMimeType);
                                            final Uri uri = FolderHelper.addImage(mActivity, checkedFile.getName(),
                                                    options.outMimeType, System.currentTimeMillis(), null, 0,
                                                    (int) checkedFile.length(), checkedFile.getAbsolutePath(), options.outWidth, options.outHeight);
                                            if (uri != null) {
                                                mActivity.runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        hideUploadProgressDialog();
                                                        addUri(uri);
                                                        if (mActivity.getEntrance() == ImagePreviewActivity.FROM_GALLERY) {
                                                            mActivity.setIsNeedRefresh(ImagePreviewActivity.REFRESH_CURRENT_AND_OTHER_GALLERY);
                                                        }
                                                        Toast.makeText(mActivity, getResources().getString(R.string.image_edit_save_success), Toast.LENGTH_SHORT).show();
                                                    }
                                                });
                                            }
                                        }
                                    }.start();
                                }
                            });
                    showUploadProgressDialog(mActivity.getString(R.string.more_menu_convert_to_gif), 100, false, true);
                    device.start();
                } catch (Exception e) {
                    Toast.makeText(mActivity, R.string.video_edit_open_failed,
                            Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

}
